﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Builders;
using System.Reflection;

namespace XTeam.Core.Abstract
{
    public class IdentityGenerator : IIdGenerator
    {
        MongoDBContext _dbContext;


        public IdentityGenerator(MongoDBContext dbContext)
        {
            _dbContext = dbContext;
        }
        public object GenerateId(object container, object document)
        {
            var table = _dbContext.GetCollection("IdentityTable");
            var modify = table.FindAndModify(Query.EQ("_id", string.Format("{0}", container)), SortBy.Null, Update.Inc("CurrentIdValue", 1), true, true);
            return modify.ModifiedDocument["CurrentIdValue"].AsInt32;
        }

        public bool IsEmpty(object id)
        {

            return (int)id < 1;
        }


    }

    public abstract class MongoDBContext
    {
        private string _connectionString = "mongodb://localhost/?safe=true";
        private string _dbName;
        protected MongoDatabase _db;
        private Dictionary<Type, string> _collectMap = new Dictionary<Type, string>();

        public MongoDatabase DataBase
        {
            get
            {
                return _db;
            }
        }

        public MongoDBContext(string connectionString, string dbName)
        {
            this._connectionString = string.IsNullOrEmpty(connectionString) ? this._connectionString : connectionString;
            this._dbName = string.IsNullOrEmpty(dbName) ? this._dbName : dbName;
            MongoServer server = MongoServer.Create(_connectionString);
            _db = server.GetDatabase("DataBase");
            this.Initial();

        }

        public MongoDBContext()
            : this(string.Empty, string.Empty)
        {
        }

        public void MapToCollection<T>(string collectName)
        {
            _collectMap.Add(typeof(T), collectName);
        }

        protected void UnMapCollection<T>()
        {
            if (_collectMap.ContainsKey(typeof(T)))
            {
                _collectMap.Remove(typeof(T));
            }
        }

        public abstract void Initial();

        public MongoCollection GetCollection(string name)
        {
            return _db.GetCollection(name);
        }

        public MongoCollection<T> GetCollection<T>(string name)
        {
            return _db.GetCollection<T>(name);
        }

        public MongoCollection<T> GetCollection<T>()
        {
            string collectName = string.Empty;

            if (!_collectMap.TryGetValue(typeof(T), out collectName))
            {
                throw new Exception("没有找到任何映射");
            }

            return _db.GetCollection<T>(collectName);
        }


    }
}
